package jnpf.engine.util;

import jnpf.base.service.DbTableService;
import jnpf.database.constant.DbFieldConst;
import jnpf.database.model.dbfield.DbFieldModel;
import jnpf.database.model.dbtable.DbTableFieldModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class ConcurrencyUtils {

	@Autowired
	private DbTableService dbTableService;

	//创建锁字段
	public void createVersion(String table, String linkId) throws Exception {
		DbTableFieldModel dbTableModel = dbTableService.getDbTableModel(linkId, table);
		List<DbFieldModel> fieldList = dbTableModel.getDbFieldModelList();
		DbFieldModel dbFieldModel = fieldList.stream().filter(f -> f.getField().equalsIgnoreCase("f_version")).findFirst().orElse(null);
		boolean hasVersion = dbFieldModel!=null;
		if (!hasVersion){
			dbFieldModel = new DbFieldModel();
			dbFieldModel = getVersionDbFieldModel(dbFieldModel);
			List<DbFieldModel> fieldOneList = new ArrayList<>();
			fieldOneList.add(dbFieldModel);
			dbTableModel.setDbFieldModelList(fieldOneList);
			dbTableModel.setUpdateNewTable(table);
			dbTableModel.setUpdateOldTable(table);
			dbTableModel.setDbLinkId(linkId);
			dbTableService.addField(dbTableModel);
		}
	}

	protected DbFieldModel getVersionDbFieldModel(DbFieldModel dbFieldModel){
		dbFieldModel.setLength("20");
		dbFieldModel.setDataType("bigint");
		dbFieldModel.setField("f_version");
		dbFieldModel.setIsPrimaryKey(false);
		dbFieldModel.setNullSign("NULL");
		dbFieldModel.setComment("乐观锁");
		return dbFieldModel;
	}

	//创建flowTaskId
	public void createFlowTaskId(String table, String linkId) throws Exception {
		DbTableFieldModel dbTableModel = dbTableService.getDbTableModel(linkId, table);
		List<DbFieldModel> fieldList = dbTableModel.getDbFieldModelList();
		DbFieldModel dbFieldModel = fieldList.stream().filter(f -> f.getField().equalsIgnoreCase("f_flowtaskid")).findFirst().orElse(null);
		boolean hasVersion = dbFieldModel!=null;
		if (!hasVersion){
			dbFieldModel = new DbFieldModel();
			dbFieldModel = getFlowTask(dbFieldModel);
			List<DbFieldModel> fieldOneList = new ArrayList<>();
			fieldOneList.add(dbFieldModel);
			dbTableModel.setDbFieldModelList(fieldOneList);
			dbTableModel.setUpdateNewTable(table);
			dbTableModel.setUpdateOldTable(table);
			dbTableModel.setDbLinkId(linkId);
			dbTableService.addField(dbTableModel);
		}
	}

	protected DbFieldModel getFlowTask(DbFieldModel dbFieldModel){
		dbFieldModel.setLength("50");
		dbFieldModel.setDataType("varchar");
		dbFieldModel.setField("f_flowtaskid");
		dbFieldModel.setIsPrimaryKey(false);
		dbFieldModel.setNullSign(DbFieldConst.NULL);
		dbFieldModel.setComment("应用id");
		return dbFieldModel;
	}


}
